package com.controller;

import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login.do")
    public String login(User user, HttpSession session) throws Exception {
        User login = userService.findLogin(user.getUserCode(), user.getUserPassword());
        if (login!=null){
            session.setAttribute("userl",login);
            return "welcome";
        }
        throw new Exception("错误密码");
    }

    @ResponseBody
    @RequestMapping("/userList.do")
    public List<User> ShowUserList(){
        List<User> list = userService.findAll();
        return list;
    }

    @RequestMapping("/userSearch.do")
    public String searchUser(String username,HttpSession session){
        if (username==null||username==""){
            return "redirect:userList.do";
        }
        List<User> list = userService.findSearchUser(username);
        session.setAttribute("userList",list);
        return "userList";
    }

    @RequestMapping("/userView.do")
    public String userView(Long id,HttpSession session){
        User user = userService.findUserById(id.intValue());
        session.setAttribute("viewuser",user);
        return "userView";
    }

    @RequestMapping("/userAdd.do")
    public String addUser(User user) throws Exception {
        /*System.out.println(user);*/
        boolean isok = userService.doAddUser(user);
        if (isok){
            return "redirect:userList.do";
        }
        return "userAdd";
    }

    @ResponseBody
    @RequestMapping("/userDelete.do")
    public boolean deleteUser(Long id){
        boolean isok = userService.doDeleteUser(id.intValue());
        return isok;
    }

    @ResponseBody
    @RequestMapping("/userUpdate.do")
    public boolean update(@RequestBody User user){
        /*System.out.println(user);*/
        boolean isok = userService.doUpdataUser(user);
        return isok;
    }

    @ResponseBody
    @RequestMapping("/userUpdateView.do")
    public User updateV(Long id){
        User user = userService.findUserById(id.intValue());
        return user;
    }

    @ExceptionHandler
    public String handler(HttpServletRequest request, Exception ex){
        //保存异常信息
        request.setAttribute("message",ex.toString());
        //返回本类出现异常对应的页面名称
        return "error";
    }
}
